package cn.tedu.ivos.repair.service.impl;

import cn.tedu.ivos.repair.mapper.RepairMapper;
import cn.tedu.ivos.repair.pojo.dto.RepairQuery;
import cn.tedu.ivos.repair.pojo.dto.RepairSaveParam;
import cn.tedu.ivos.repair.pojo.entity.Repair;
import cn.tedu.ivos.repair.pojo.vo.RepairVO;
import cn.tedu.ivos.repair.service.RepairService;
import cn.tedu.ivos.user.mapper.UserMapper;
import cn.tedu.ivos.user.pojo.vo.UserVO;
import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos.vehicle.pojo.entity.Vehicle;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class RepairServiceImpl implements RepairService {
    @Autowired
    private RepairMapper repairMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private VehicleMapper vehicleMapper;

    @Override
    public List<RepairVO> selectRepair(RepairQuery repairQuery) {
        log.debug("查询报修业务：repairQuery={}", repairQuery);
        List<RepairVO> list = repairMapper.selectRepair(repairQuery);
        log.debug("查询报修业务：list={}", list);
        return list;
    }

    @Override
    public void savaRepair(RepairSaveParam repairSaveParam) {
        log.debug("保存报修业务：repairSaveParam={}", repairSaveParam);
        Repair repair = new Repair();
        BeanUtils.copyProperties(repairSaveParam,repair);
        UserVO userVO =userMapper.selectByUsername(repair.getUsername());
        repair.setUserId(userVO.getId());
        VehicleQuery vehicleQuery = new VehicleQuery();
        vehicleQuery.setLicense(repairSaveParam.getLicense());
        List<VehicleVO> vehicleList = vehicleMapper.selectVehicle(vehicleQuery);
        repair.setVehicleId(vehicleList.get(0).getId());
        if(repair.getId()==null){
            repair.setCreateTime(new Date());
            repairMapper.insert(repair);
        }else{
            repair.setUpdateTime(new Date());
            repairMapper.update(repair);
        }
        Vehicle vehicle = new Vehicle();
        vehicle.setId(repair.getVehicleId());
        vehicle.setUpdateTime(new Date());
        if("1".equals(repair.getStatus())){
            vehicle.setStatus("3");
            vehicleMapper.update(vehicle);
        }else{
            vehicle.setStatus("1");
            vehicleMapper.update(vehicle);
        }
    }

    @Override
    public void deleteRepair(Long id) {
        log.debug("删除报修业务：id={}", id);
        repairMapper.delete(id);
    }
}
